package com.repeat.gateway.filters;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.nacos.common.packagescan.resource.AntPathMatcher;
import com.repeat.gateway.enums.GatewayEnum;
import com.repeat.gateway.response.GatewayResponse;

import com.shop.security.config.IgnoreUrlsConfig;
import com.shop.security.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class GlobalFilters implements GlobalFilter , Ordered{

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    // 创建 AntPathMatcher 实例
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestPath = exchange.getRequest().getPath().value();
        log.info("全局过滤器生效：请求路径={}", requestPath);
        // 放行不需要认证的URL
//        if (ignoreUrlsConfig.getUrls().stream().anyMatch(requestPath::startsWith)) {
//            return chain.filter(exchange);
//        }
        // 遍历所有需要忽略的URL模式
        for (String pattern : ignoreUrlsConfig.getUrls()) {
            // 使用 antPathMatcher 进行模式匹配
            if (antPathMatcher.match(pattern, requestPath)) {
                log.info("路径 '{}' 匹配到忽略模式 '{}'，直接放行。", requestPath, pattern);
                // 如果路径匹配到了任一忽略模式，则直接放行
                return chain.filter(exchange);
            }
        }
        String authorization = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        // 验证授权头
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            log.info("AuthFail: 授权参数问题");
            return buildErrorResponse(exchange, GatewayEnum.INVALID_TOKEN);
        }
        String jwt = authorization.substring(7);
        try {
            if (jwtUtils.validateToken(jwt)) {
                log.info("令牌验证通过");
                return chain.filter(exchange);
            } else {
                return buildErrorResponse(exchange, GatewayEnum.INVALID_TOKEN);
            }
        } catch (Exception e) {
            log.error("令牌验证失败: {}", e.getMessage());
            return buildErrorResponse(exchange, GatewayEnum.TOKEN_BLACKLISTED);
        }
    }
    /**
     * 构建统一错误响应
     */
    private Mono<Void> buildErrorResponse(ServerWebExchange exchange, GatewayEnum exceptionEnum) {
        // 创建异常响应对象
        GatewayResponse response = new GatewayResponse(
                exceptionEnum.getCode(),
                exceptionEnum.getMsg(),
                null
        );

        // 序列化时保留 null 字段
        String jsonResponse = JSON.toJSONString(
                response,
                SerializerFeature.WriteMapNullValue  // 关键配置：保留 null 字段
        );
        // 设置响应信息
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 写入响应体
        DataBuffer buffer = exchange.getResponse()
                .bufferFactory()
                .wrap(jsonResponse.getBytes(StandardCharsets.UTF_8));

        return exchange.getResponse().writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
